package com.asideal.framework.security.filter;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.asideal.common.constant.HttpStatus;
import com.asideal.common.utils.SecurityUtils;
import com.asideal.common.utils.ServletUtils;
import com.asideal.common.utils.StringUtils;
import com.asideal.framework.security.LoginUser;
import com.asideal.framework.security.service.TokenService;
import com.asideal.framework.web.domain.AjaxResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
/**
 * token过滤器 验证token有效性
 */
@Component
public class AccessFilter extends ZuulFilter {
	 @Autowired
    private TokenService tokenService;
	public Object run() throws ZuulException {
		// 获取上下文
		RequestContext currentContext = RequestContext.getCurrentContext();
		HttpServletRequest request = currentContext.getRequest();
		
		LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(loginUser);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//        }else {
//        	int code = HttpStatus.UNAUTHORIZED;
//            String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
//            currentContext.setSendZuulResponse(false);
//			currentContext.setResponseStatusCode(code);
//            currentContext.setResponseBody(msg);
//            return null;
        }
		// 否则正常执行业务逻辑.....
		return null;
	}

	// 判断过滤器是否生效
	public boolean shouldFilter() {

		return true;
	}

	// 过滤器的执行顺序。当请求在一个阶段的时候存在多个多个过滤器时，需要根据该方法的返回值依次执行
	public int filterOrder() {

		return 0;
	}

	// 过滤器类型 pre 表示在 请求之前进行拦截
	public String filterType() {

		return "pre";
	}

}
